import { checkNumPot, checkInterNum, checkHalf } from '@/utils/validate';

// wooc基础表单验证
export function formRules(checkStr, that) {
  return {
    name: [{ required: true, validator: checkStr, trigger: 'blur' }],
    salePrice: [
      {
        required: true,
        validator: (rule, value, callback) =>
          checkSalePrice(
            rule,
            value,
            callback,
            that.formData.regularPrice,
            that
          ),
        trigger: 'blur'
      }
    ],
    regularPrice: [
      {
        required: true,
        validator: (rule, value, callback) =>
          checkRegularPrice(
            rule,
            value,
            callback,
            that.formData.salePrice,
            that
          ),
        trigger: 'blur'
      }
    ],
    taxClass: [
      {
        required: true,
        message: 'please select',
        trigger: 'change'
      }
    ],
    sku: [{ required: true, validator: checkHalf, trigger: 'blur' }],
    barcode: [{ required: true, validator: checkStr, trigger: 'blur' }],
    saleTime: [
      {
        validator: (rule, value, callback) =>
          checkSaleTime(rule, value, callback, that),
        trigger: 'blur'
      }
    ],
    offSaleTime: [
      {
        validator: (rule, value, callback) =>
          checkOffsaleTime(rule, value, callback, that),
        trigger: 'blur'
      }
    ],
    inventoryQuantity: [
      { required: true, validator: checkInterNum, trigger: 'blur' }
    ],
    quantity: [{ required: true, validator: checkInterNum, trigger: 'blur' }],
    lowInventoryThreshold: [
      { required: true, validator: checkInterNum, trigger: 'blur' }
    ],
    weight: [{ required: true, validator: checkNumPot, trigger: 'blur' }],
    height: [{ required: true, validator: checkNumPot, trigger: 'blur' }],
    width: [{ required: true, validator: checkNumPot, trigger: 'blur' }],
    length: [{ required: true, validator: checkNumPot, trigger: 'blur' }],
    shippingClassId: [
      {
        required: true,
        message: 'please select',
        trigger: 'change'
      }
    ],
    productCategoryIds: [
      {
        required: true,
        message: 'please select the category',
        trigger: 'change'
      }
    ],
    productTagIds: [
      {
        required: true,
        message: 'please select/add the tag',
        trigger: 'change'
      }
    ],
    vendorId: [
      {
        required: true,
        message: 'please select the vendor',
        trigger: 'change'
      }
    ]
  };
}

// shopify基础表单验证
export function shopifyRules(checkStr, that) {
  return {
    name: [{ required: true, validator: checkStr, trigger: 'blur' }],
    storeId: [
      { required: true, message: 'Please select store', trigger: 'change' }
    ],
    salePrice: [
      {
        required: true,
        validator: checkNumPot,
        trigger: ['blur', 'change']
      }
    ],
    regularPrice: [
      {
        required: true,
        validator: checkNumPot,
        trigger: ['blur', 'change']
      }
    ],
    sku: [{ required: true, validator: checkHalf, trigger: 'blur' }],
    barcode: [
      {
        required: true,
        validator: checkStr,
        trigger: ['blur', 'change']
      }
    ],
    inventoryQuantity: [
      { required: true, validator: checkInterNum, trigger: 'blur' }
    ],
    quantity: [
      {
        required: true,
        validator: checkInterNum,
        trigger: ['blur', 'change']
      }
    ],
    weight: [
      {
        required: true,
        validator: checkNumPot,
        trigger: ['blur', 'change']
      }
    ],
    productCategoryIds: [
      {
        required: true,
        message: 'Please select/add the category',
        trigger: 'change'
      }
    ],
    productTagIds: [
      {
        required: true,
        message: 'Please select/add the tag',
        trigger: 'change'
      }
    ],
    vendorId: [
      {
        required: true,
        message: 'Please select the vendor',
        trigger: 'change'
      }
    ]
  };
}

// 变种批量编辑项(common)
export const batchOption = [
  { label: 'salePrice', title: 'Sale price', type: 'input' },
  { label: 'regularPrice', title: 'Regular price', type: 'input' },
  { label: 'barcode', title: 'Bar code', type: 'input' },
  { label: 'isVirtual', title: 'Is virtual', type: 'checkbox' },
  { label: 'weight', title: 'Weight', type: 'input' },
  { label: 'length', title: 'Length', type: 'input' },
  { label: 'width', title: 'Width', type: 'input' },
  { label: 'height', title: 'Height', type: 'input' },
  { label: 'isManage', title: 'Stock', type: 'checkbox' },
  { label: 'quantity', title: 'Quantity', type: 'input' },
  {
    label: 'allowBackorders',
    title: 'Allowed backorders',
    type: 'checkbox'
  },
  {
    label: 'lowInventoryThreshold',
    title: 'Low stock threshold',
    type: 'input'
  },
  {
    label: 'isSoldIndividually',
    title: 'Sold individually',
    type: 'checkbox'
  }
];

// 切换复选框状态，清空对应数据(common)
export function toggleCheck(val, label, that) {
  if (val === 0) {
    switch (label) {
      case 'isManageInventory':
        // that.$set(that.formData, 'inventoryQuantity', 0)
        // that.$set(that.formData, 'lowInventoryThreshold', 0)
        delete that.formData.inventoryQuantity;
        delete that.formData.lowInventoryThreshold;
        that.$set(that.formData, 'allowBackorders', 0);
        break;
      case 'allowBackorders':
        delete that.formData.lowInventoryThreshold;
      // that.$set(that.formData, 'lowInventoryThreshold', 0)
    }
  } else {
    if (label === 'isVirtual') {
      that.$set(that.formData, 'weight', '0');
      that.$set(that.formData, 'width', '0');
      that.$set(that.formData, 'height', '0');
      that.$set(that.formData, 'length', '0');
    }
  }
}

// watch规格信息变化(common)
export function watchSpecifications(newVal, that, productType) {
  const newSpecificationData = [];
  const valuesArr = [];
  const variantNameIds = [];
  that.selectOptions = [];
  for (let i = 0; i < newVal.length; i++) {
    if (newVal[i].parent !== '' && newVal[i].son.length !== 0) {
      valuesArr.push(newVal[i].son);
      variantNameIds.push(
        that.specList.find((item) => item.name === newVal[i].parent)['id']
      );
    }
    for (let j = 0; j < that.specList.length; j++) {
      if (that.specList[j].name === newVal[i].parent) {
        that.selectOptions[i] = that.specList[j].listLeaf;
      }
    }
  }
  if (valuesArr[0]) {
    var res0 = [];
    for (let i = 0; i < valuesArr[0].length; i++) {
      res0.push(valuesArr[0][i]);
    }
  }
  if (valuesArr[1]) {
    var res1 = [];
    for (let i = 0; i < res0.length; i++) {
      for (let j = 0; j < valuesArr[1].length; j++) {
        res1.push(res0[i] + '_' + valuesArr[1][j]);
      }
    }
  }
  if (valuesArr[2]) {
    var res2 = [];
    for (let i = 0; i < res1.length; i++) {
      for (let j = 0; j < valuesArr[2].length; j++) {
        res2.push(res1[i] + '_' + valuesArr[2][j]);
      }
    }
  }
  const resArr = res2 || res1 || res0 || [];
  resArr.forEach((item) => {
    if (item) {
      var variantValueIds = [];
      var text = '';
      var arr = item.split('_');
      for (let j = 0; j < arr.length; j++) {
        var obj = that.specList.find((item) => item.id === variantNameIds[j]);
        if (obj.listLeaf.length > 0) {
          for (let i = 0; i < obj.listLeaf.length; i++) {
            if (arr[j] === obj.listLeaf[i].name) {
              variantValueIds.push(obj.listLeaf[i].id);
              if (j < arr.length - 1) {
                text = text + obj.listLeaf[i].id + ',';
              } else {
                text = text + obj.listLeaf[i].id;
              }
            }
          }
        }
      }
    }
    that.formData['productVariantIds'] = variantNameIds;
    if (productType === 'wooc') {
      newSpecificationData.push({
        titleIds: text,
        titleValues: item,
        variantSku: that.formData.sku
          ? that.formData.sku + '_' + item
          : '_' + item,
        thumbnailUri: '',
        salePrice: that.formData.salePrice || null,
        regularPrice: that.formData.regularPrice || null,
        taxStatus: that.formData.taxStatus || 1,
        taxClass: that.formData.taxClass || 'Standard',
        isVirtual: that.formData.isVirtual || 0,
        weight: that.formData.weight || '0',
        isDimensions: that.formData.isDimensions || 1,
        height: that.formData.height || '0',
        width: that.formData.width || '0',
        length: that.formData.length || '0',
        shippingClassId: that.formData.shippingClassId || 0,
        isManage: that.formData.isManageInventory || 0,
        quantity: that.formData.inventoryQuantity || 0,
        allowBackorders: that.formData.allowBackorders || 0,
        lowInventoryThreshold: that.formData.lowInventoryThreshold || 0,
        status: that.formData.inventoryStatus || 0,
        barcode: '',
        isSoldIndividually: 0
      });
    } else if (productType === 'shopify') {
      newSpecificationData.push({
        titleIds: text,
        titleValues: item,
        variantSku: that.formData.sku
          ? that.formData.sku + '_' + item
          : '_' + item,
        thumbnailUri: '',
        salePrice: that.formData.salePrice || null,
        regularPrice: that.formData.regularPrice || null,
        taxStatus: that.formData.taxStatus || 0,
        isVirtual: that.formData.isVirtual || 0,
        weight: that.formData.weight || '0',
        isManage: that.formData.isManageInventory || 0,
        quantity: that.formData.inventoryQuantity || 0,
        barcode: ''
      });
    }
  });
  newSpecificationData.forEach((item, index) => {
    if (that.cloneSpecificationData.length > 0) {
      for (let i = 0; i < that.cloneSpecificationData.length; i++) {
        if (that.cloneSpecificationData[i].titleIds === item.titleIds) {
          newSpecificationData[index] = that.cloneSpecificationData[i];
        }
      }
    }
  });
  that.$set(
    that.formData,
    'specificationData',
    that.firstRandom &&
      newSpecificationData.length > that.cloneSpecificationData.length
      ? that.cloneSpecificationData
      : newSpecificationData
  );
  that.firstRandom = false;
  that.$nextTick(() => {
    that.$refs['productForm'].clearValidate();
  });
}

// sku变动时，改变变种sku
export function changeVariantSku(val, that) {
  if (that.formData.specificationData.length > 0) {
    // 有变种信息时，改变变种SKU
    that.formData.specificationData.forEach((item) => {
      if (item.variantSku[0] === '_') {
        item.variantSku = val + item.variantSku;
      } else {
        const arr = item.variantSku.split('_');
        arr[0] = val;
        item.variantSku = arr.join('_');
      }
    });
  }
}

// wooc商品售卖价格(加入比较)
function checkSalePrice(rule, value, callback, str, that) {
  const arr = rule.field.split('.');
  const specNum = arr.length > 1 ? Number(arr[1]) : null;
  if (specNum !== null) {
    str = that.formData.specificationData[specNum].regularPrice;
  }
  const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
  if (!value) {
    return callback(new Error('fill in Numbers'));
  } else if (!reg.test(value)) {
    return callback(new Error('up to 2 decimal'));
  } else if (value * 100 > 1000000) {
    return callback(new Error('too large'));
  } else if (str && Number(value) >= Number(str)) {
    if (specNum !== null) {
      that.formData.specificationData[specNum].salePrice = null;
    } else {
      that.formData.salePrice = null;
    }
    return callback(new Error('less than regular price'));
  } else {
    callback();
  }
}

// wooc商品比较价格(加入比较)
function checkRegularPrice(rule, value, callback, str, that) {
  const arr = rule.field.split('.');
  const specNum = arr.length > 1 ? Number(arr[1]) : null;
  if (specNum !== null) {
    str = that.formData.specificationData[specNum].salePrice;
  }
  const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
  if (!value) {
    return callback(new Error('fill in Numbers'));
  } else if (!reg.test(value)) {
    return callback(new Error('up to 2 decimal'));
  } else if (value * 100 > 1000000) {
    return callback(new Error('too large'));
  } else if (str && Number(str) >= Number(value)) {
    if (specNum !== null) {
      that.formData.specificationData[specNum].regularPrice = null;
    } else {
      that.formData.regularPrice = null;
    }
    return callback(new Error('more than sale price'));
  } else {
    callback();
  }
}

// wooc商品售卖时间(加入比较)
function checkSaleTime(rule, value, callback, that) {
  const specNum = Number(rule.field.split('.')[1]);
  const str = that.formData.specificationData[specNum].offSaleTime;
  if (!value || !str) {
    callback();
  } else {
    const saleTimestamp = new Date(value).getTime();
    const offTimestamp = new Date(str).getTime();
    if (saleTimestamp > offTimestamp) {
      return callback(new Error('No more than the offsale time'));
    } else {
      callback();
    }
  }
}

// wooc商品停售时间(加入比较)
function checkOffsaleTime(rule, value, callback, that) {
  const specNum = Number(rule.field.split('.')[1]);
  const str = that.formData.specificationData[specNum].saleTime;
  if (!value || !str) {
    callback();
  } else {
    const offTimestamp = new Date(value).getTime();
    const saleTimestamp = new Date(str).getTime();
    if (offTimestamp < saleTimestamp) {
      return callback(new Error('No less than the sale time'));
    } else {
      callback();
    }
  }
}
